package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    @Override
    public Result queryBlogById(Long id) {
        // 查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        // blog封装用户
        queryBlogUserInfo(blog);
        // 查询用户是否点赞了blog
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return;
        }
        Long userId = user.getId();
        String key = "blog:liked:" + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            queryBlogUserInfo(blog);
            isBlogLiked(blog);
        });
        /*
        records.forEach(blog ->{
        queryBlogUserInfo(blog);
        });
         */
        return Result.ok(records);
    }

    @Override
    public Result likeBlog(Long id) {

        // TODO 有线程安全问题

        // 查询用户信息
        Long userId = UserHolder.getUser().getId();
        // 判断用户是否已经点赞
        String key = "blog:liked:" + id;
        Double isHas = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (isHas != null) {
            // 已经点赞, 取消点赞
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (!isSuccess) {
                return Result.fail("取消点赞失败");
            }
            stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            return Result.ok("取消成功");
        } else {
            // 没有点赞, 点赞
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (!isSuccess) {
                return Result.ok("点赞失败");
            }
            stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            return Result.ok("点赞成功");
        }
    }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = "blog:liked:" + id;
        // zset默认score从小到大排
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (CollectionUtil.isEmpty(top5)) {
            return Result.ok(Collections.emptyList());
        }
        // 根据top5查id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",", ids);
        // 根据id查询用户
        List<User> users = userService.query()
                .in("id", ids)
                .last("ORDER BY FIELD( id," + idStr + ")")
                .list();
        if (CollectionUtil.isEmpty(users)) {
            return Result.fail("用户不存在");
        }
        List<UserDTO> userDTOList = users.stream().map(user -> {
            return BeanUtil.copyProperties(user, UserDTO.class);
        }).collect(Collectors.toList());
        return Result.ok(userDTOList);
    }

    @Override
    public Result saveBlog(Blog blog) {
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        boolean isSuccess = save(blog);
        if (!isSuccess) {
            return Result.fail("发布失败");
        }
        // 查询笔记作者的所有粉丝
        List<Follow> followUserList = followService.query().eq("follow_user_id", blog.getUserId()).list();
        for (Follow follow : followUserList) {
            Long userId = follow.getUserId();
            String key = RedisConstants.FEED_KEY + userId;
            // 将作者笔记id发送到每个粉丝的收件箱(redis中的zsort结构)
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples =
                stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        // 判空
        if (CollectionUtil.isEmpty(typedTuples)) {
            return Result.ok();
        }
        // 解析数据
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minScore = max;
        int os = offset; // 和最小分数相同的分数个数
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            // blogId
            String blogId = typedTuple.getValue();
            ids.add(Long.valueOf(blogId));
            // 分数 最后一个一定是最小时间
            long time = typedTuple.getScore().longValue();
            if (minScore == time) {
                os++;
            } else {
                minScore = time;
                os = 1;
            }
        }
        // 根据id查询blog
        String idStr = StrUtil.join(",", ids); // 在上面的for循环里拼接也行
        // listByid不保持顺序
        List<Blog> blogs = query().in("id", ids)
                .last("ORDER BY FIELD( id," + idStr + ")")
                .list();
        // blog中的一些外来属性填充
        for (Blog blog : blogs) {
            queryBlogUserInfo(blog);
            isBlogLiked(blog);
        }
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minScore);
        return Result.ok(scrollResult);
    }

    private void queryBlogUserInfo(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
}
